import { fetchSubProjectEmployees, updateSubProject, addSubemp, deleteSubemp } from '../../../api/project';
import { getEmployeeList } from '../../../api/employee';

Page({
  data: {
    subProjectId: null,
    subProjectName: '',
    employeeList: [],
    subProjectEmployees: [],
    newEmployee: '',
    editSubProjectName: '',
    showEmployeeModal: false
  },

  onLoad(options) {
    const { subProjectId, subProjectName } = options;
    this.setData({ subProjectId, subProjectName, editSubProjectName: subProjectName });
    this.fetchSubProjectEmployees(subProjectId);
    this.getEmployeeList();
  },

  fetchSubProjectEmployees(subProjectId) {
    fetchSubProjectEmployees(subProjectId).then(response => {
      if (response.code === 1) {
        this.setData({
          subProjectEmployees: response.data
        }, () => {
          this.updateEmployeeListState();
        });
      } else {
        console.error('Failed to fetch sub-project employees');
      }
    }).catch(error => {
      console.error('Error fetching sub-project employees:', error);
    });
  },

  getEmployeeList() {
    getEmployeeList({}).then(response => {
      if (response.code === 1) {
        this.setData({
          employeeList: response.data
        }, () => {
          this.updateEmployeeListState();
        });
      } else {
        console.error('Failed to fetch employees');
      }
    }).catch(error => {
      console.error('Error fetching employees:', error);
    });
  },

  updateEmployeeListState() {
    const { employeeList, subProjectEmployees } = this.data;
    const updatedEmployeeList = employeeList.map(employee => ({
      ...employee,
      isAdded: subProjectEmployees.some(subEmp => subEmp.employeeId === employee.id)
    }));
    this.setData({ employeeList: updatedEmployeeList });
  },

  showEmployeeModal() {
    this.setData({
      showEmployeeModal: true
    });
  },

  hideEmployeeModal() {
    this.setData({
      showEmployeeModal: false
    });
  },

  addEmployeeToSubProject(event) {
    const employee = event.currentTarget.dataset.employee;
    const { subProjectId } = this.data;
    wx.showLoading({
      title: '添加中...',
    });
    addSubemp({ projectsId: subProjectId, employeeId: employee.id }).then(response => {
      wx.hideLoading();
      if (response.code === 1) {
        wx.showToast({
          title: '人员添加成功',
          icon: 'success'
        });
        this.fetchSubProjectEmployees(subProjectId);
        this.getEmployeeList();
      } else {
        console.error('Failed to add employee');
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('Error adding employee:', error);
    });
  },

  deleteEmployeeFromSubProject(event) {
    const employeeId = event.currentTarget.dataset.employee.employeeId;
    const { subProjectId } = this.data;
    wx.showLoading({
      title: '删除中...',
    });
    deleteSubemp({ projectsId: subProjectId, employeeId: employeeId }).then(response => {
      wx.hideLoading();
      if (response.code === 1) {
        wx.showToast({
          title: '人员删除成功',
          icon: 'success'
        });
        this.fetchSubProjectEmployees(subProjectId);
        this.getEmployeeList();
      } else {
        console.error('Failed to delete employee');
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('Error deleting employee:', error);
    });
  },

  onInputChange(event) {
    this.setData({
      editSubProjectName: event.detail.value
    });
  },

  confirmEditSubProject() {
    const { subProjectId, editSubProjectName } = this.data;
    if (!editSubProjectName) {
      wx.showToast({
        title: '小项目名称不能为空',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '更新中...',
    });
    updateSubProject({ id: subProjectId, name: editSubProjectName }).then(response => {
      wx.hideLoading();
      if (response.code === 1) {
        wx.showToast({
          title: '小项目更新成功',
          icon: 'success'
        });
        this.setData({ subProjectName: editSubProjectName });

        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('updateSubProjectName', { id: subProjectId, name: editSubProjectName });
        wx.navigateBack();
      } else {
        console.error('Failed to update sub-project');
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('Error updating sub-project:', error);
    });
  },

  preventTouchMove() {
    // 空方法，用于捕获和阻止 touchmove 事件
  }
});
